//
//  CJUserAccount.swift
//  SwiftDemo
//
//  Created by Chris on 2017/7/5.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit


/// 文件位置
private let accountFilePath: NSString = "useraccount.json"

/// 用户信息
class CJUserAccount: NSObject {

    /// 访问令牌
    var access_token: String?
    
    /// 用户Id
    var uid: String?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像
    var avatar_large: String?
    
    /// 过期时间
    var expiresDate: Date?
    
    /// access_token访问令牌的时效, 过期失效
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    override init() {
        super.init()
        
        let path: String = accountFilePath.appendingDocumentDirectory() as String
        // 从沙盒中获取字典
        guard let data = NSData(contentsOfFile: path), let dict = try? JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as? [String: Any] else {
            return
        }
        // 字典转模型
        yy_modelSet(with: dict ?? [:])
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            
            uid = nil
            access_token = nil
            // 删除沙盒中过期用户信息
            _ = try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    /// 保存模型到沙盒
    func saveAccount() {
        
        // 模型转json
        var dict = yy_modelToJSONObject() as? [String: Any] ?? [:]
        // 删除过期时间字段
        dict.removeValue(forKey: "expires_in")
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return
        }
        let filePath: NSString = accountFilePath.appendingDocumentDirectory()
        
        (data as NSData).write(toFile: filePath as String, atomically: true)
    }
    
    override var description: String {
        return yy_modelDescription()
    }
    
}
